<!doctype html>



  


<html class="theme-next muse use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="上次浅显的分析了Timer及TimerTask的调度原理，这里我们再来看一下另一种定时调度方式ScheduledThreadPoolExecutor的内部执行原理。


ScheduledThreadPoolExecutor调度方式
阻塞队列DelayedWorkQueue的实现
ScheduledFutureTask控制调度过程
总结">
<meta property="og:type" content="article">
<meta property="og:title" content="java定时任务（2）">
<meta property="og:url" content="http://yoursite.com/2016/08/28/java定时任务（2）/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="上次浅显的分析了Timer及TimerTask的调度原理，这里我们再来看一下另一种定时调度方式ScheduledThreadPoolExecutor的内部执行原理。


ScheduledThreadPoolExecutor调度方式
阻塞队列DelayedWorkQueue的实现
ScheduledFutureTask控制调度过程
总结">
<meta property="og:updated_time" content="2017-01-19T07:14:13.208Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java定时任务（2）">
<meta name="twitter:description" content="上次浅显的分析了Timer及TimerTask的调度原理，这里我们再来看一下另一种定时调度方式ScheduledThreadPoolExecutor的内部执行原理。


ScheduledThreadPoolExecutor调度方式
阻塞队列DelayedWorkQueue的实现
ScheduledFutureTask控制调度过程
总结">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/08/28/java定时任务（2）/"/>

  <title> java定时任务（2） | 个人博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">个人博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">随便写点什么</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                java定时任务（2）
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T16:00:43+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/08/28/java定时任务（2）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/08/28/java定时任务（2）/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<p>上次浅显的分析了Timer及TimerTask的调度原理，这里我们再来看一下另一种定时调度方式<strong>ScheduledThreadPoolExecutor</strong>的内部执行原理。</p>
<blockquote>
<ul>
<li>ScheduledThreadPoolExecutor调度方式</li>
<li>阻塞队列DelayedWorkQueue的实现</li>
<li>ScheduledFutureTask控制调度过程</li>
<li>总结</li>
</ul>
</blockquote>
<hr>
<a id="more"></a>
<h2 id="ScheduledThreadPoolExecutor调度方式"><a href="#ScheduledThreadPoolExecutor调度方式" class="headerlink" title="ScheduledThreadPoolExecutor调度方式"></a>ScheduledThreadPoolExecutor调度方式</h2><p>类似于Timer，它的调度方式也有4种，我们抽出其中一种来具体分析。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//一次性任务，无返回值</span></div><div class="line"><span class="keyword">public</span> ScheduledFuture&lt;?&gt; schedule(Runnable command,</div><div class="line">                                       <span class="keyword">long</span> delay,</div><div class="line">                                       TimeUnit unit) &#123;...&#125;</div><div class="line"></div><div class="line"><span class="comment">//一次性任务，有返回值</span></div><div class="line"><span class="keyword">public</span> &lt;V&gt; <span class="function">ScheduledFuture&lt;V&gt; <span class="title">schedule</span><span class="params">(Callable&lt;V&gt; callable,</span></span></div><div class="line">                                           <span class="keyword">long</span> delay,</div><div class="line">                                           TimeUnit unit) &#123;...&#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">public</span> ScheduledFuture&lt;?&gt; scheduleAtFixedRate(Runnable command,</div><div class="line">                                                  <span class="keyword">long</span> initialDelay,</div><div class="line">                                                  <span class="keyword">long</span> period,</div><div class="line">                                                  TimeUnit unit) &#123;...&#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">public</span> ScheduledFuture&lt;?&gt; scheduleWithFixedDelay(Runnable command,</div><div class="line">                                                     <span class="keyword">long</span> initialDelay,</div><div class="line">                                                     <span class="keyword">long</span> delay,</div><div class="line">                                                     TimeUnit unit)&#123;...&#125;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>我们取<strong>scheduleWithFixedDelay</strong>作为切入点来进行分析。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> ScheduledFuture&lt;?&gt; scheduleWithFixedDelay(Runnable command,</div><div class="line">                                                     <span class="keyword">long</span> initialDelay,</div><div class="line">                                                     <span class="keyword">long</span> delay,</div><div class="line">                                                     TimeUnit unit) &#123;</div><div class="line">        <span class="keyword">if</span> (command == <span class="keyword">null</span> || unit == <span class="keyword">null</span>)</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</div><div class="line">        <span class="keyword">if</span> (delay &lt;= <span class="number">0</span>)</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException();</div><div class="line">        ScheduledFutureTask&lt;Void&gt; sft =</div><div class="line">            <span class="keyword">new</span> ScheduledFutureTask&lt;Void&gt;(command,</div><div class="line">                                          <span class="keyword">null</span>,</div><div class="line">                                          triggerTime(initialDelay, unit),</div><div class="line">                                          unit.toNanos(-delay));</div><div class="line">        RunnableScheduledFuture&lt;Void&gt; t = decorateTask(command, sft);</div><div class="line">        sft.outerTask = t;</div><div class="line">        delayedExecute(t);</div><div class="line">        <span class="keyword">return</span> t;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"><span class="comment">//将Runnable适配成FutureTask</span></div><div class="line">ScheduledFutureTask&lt;Void&gt; sft =</div><div class="line">            <span class="keyword">new</span> ScheduledFutureTask&lt;Void&gt;(command,</div><div class="line">                                          <span class="keyword">null</span>,</div><div class="line">                                          triggerTime(initialDelay, unit),</div><div class="line">                                          unit.toNanos(-delay));</div><div class="line"></div><div class="line"><span class="comment">//由于是将一个无返回值的Runnable包装成一个FutureTask，所以传入一个null作为返回值</span></div><div class="line"> ScheduledFutureTask(Runnable r, V result, <span class="keyword">long</span> ns, <span class="keyword">long</span> period) &#123;</div><div class="line">            <span class="keyword">super</span>(r, result);</div><div class="line">            <span class="keyword">this</span>.time = ns;			<span class="comment">//设置执行时间</span></div><div class="line">            <span class="keyword">this</span>.period = period;	<span class="comment">//设置时间片</span></div><div class="line">            <span class="keyword">this</span>.sequenceNumber = sequencer.getAndIncrement();</div><div class="line">        &#125;</div><div class="line"></div><div class="line"><span class="comment">//Executors.callable(）是真正进行Runnable与FutureTask适配的函数</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="title">FutureTask</span><span class="params">(Runnable runnable, V result)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>.callable = Executors.callable(runnable, result);</div><div class="line">        <span class="keyword">this</span>.state = NEW;       <span class="comment">// ensure visibility of callable</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; <span class="function">Callable&lt;T&gt; <span class="title">callable</span><span class="params">(Runnable task, T result)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (task == <span class="keyword">null</span>)</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</div><div class="line">        <span class="keyword">return</span> <span class="keyword">new</span> RunnableAdapter&lt;T&gt;(task, result);</div><div class="line">    &#125;    </div><div class="line"></div><div class="line"><span class="comment">//call()就不多做介绍了，由FutureTask的call来掉内部Runnable的run()</span></div><div class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">RunnableAdapter</span>&lt;<span class="title">T</span>&gt; <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">T</span>&gt; </span>&#123;</div><div class="line">        <span class="keyword">final</span> Runnable task;</div><div class="line">        <span class="keyword">final</span> T result;</div><div class="line">        RunnableAdapter(Runnable task, T result) &#123;</div><div class="line">            <span class="keyword">this</span>.task = task;</div><div class="line">            <span class="keyword">this</span>.result = result;</div><div class="line">        &#125;</div><div class="line">        <span class="function"><span class="keyword">public</span> T <span class="title">call</span><span class="params">()</span> </span>&#123;</div><div class="line">            task.run();</div><div class="line">            <span class="keyword">return</span> result;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">   	<span class="comment">//修改或替换用于执行一个可运行的任务。</span></div><div class="line">   	<span class="comment">//这个方法可以用来覆盖具体类以管理内部任务。</span></div><div class="line">   	<span class="comment">//默认实现仅返回给定的任务。</span></div><div class="line">    RunnableScheduledFuture&lt;Void&gt; t = decorateTask(command, sft);</div><div class="line"></div><div class="line">    <span class="keyword">protected</span> &lt;V&gt; <span class="function">RunnableScheduledFuture&lt;V&gt; <span class="title">decorateTask</span><span class="params">(</span></span></div><div class="line">        Runnable runnable, RunnableScheduledFuture&lt;V&gt; task) &#123;</div><div class="line">        <span class="keyword">return</span> task;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">//这里之所以先将task放入队列，再由worker去取出并运行，是因为task有可能并不期望当下就被运行，而是期望一段时间的延迟后再开始运行。</span></div><div class="line"><span class="comment">//同时一个task被创建后直接运行，也是不合理的一种行为。</span></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">delayedExecute</span><span class="params">(RunnableScheduledFuture&lt;?&gt; task)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (isShutdown())		<span class="comment">//线程池状态是否正常</span></div><div class="line">            reject(task);		<span class="comment">//拒绝任务，根据拒绝策略，通常有1.直接丢弃 2.抛异常 3.新建一个线程来执行 4.类似于LRU，丢弃队列中最久的一个任务</span></div><div class="line">        <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">super</span>.getQueue().add(task);			<span class="comment">//先加入BlockingQueue，该队列默认在ThreadPoolExecutor中实现，但这里提供了DelayedWorkQueue代替默认实现</span></div><div class="line">            <span class="keyword">if</span> (isShutdown() &amp;&amp;</div><div class="line">                !canRunInCurrentRunState(task.isPeriodic()) &amp;&amp;		<span class="comment">//当task已经被加入队列，但是线程池挂了，根据status来决定，取消并删除在队列中的task。</span></div><div class="line">                remove(task))</div><div class="line">                task.cancel(<span class="keyword">false</span>);</div><div class="line">            <span class="keyword">else</span></div><div class="line">                ensurePrestart();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">//其实就是保证至少有一个worker已经启动</span></div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">ensurePrestart</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">int</span> wc = workerCountOf(ctl.get());</div><div class="line">        <span class="keyword">if</span> (wc &lt; corePoolSize)</div><div class="line">            addWorker(<span class="keyword">null</span>, <span class="keyword">true</span>);</div><div class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (wc == <span class="number">0</span>)</div><div class="line">            addWorker(<span class="keyword">null</span>, <span class="keyword">false</span>);</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>至此，一个定时任务就被加入DelayedWorkQueue队列了，而调度任务的线程由ThreadPoolExecutor提供。<br>但是到此为此还并没有实现延迟调度的功能。<br>接下来说说DelayedWorkQueue是如何实现延迟调度的。</p>
</blockquote>
<hr>
<h2 id="阻塞队列DelayedWorkQueue的实现"><a href="#阻塞队列DelayedWorkQueue的实现" class="headerlink" title="阻塞队列DelayedWorkQueue的实现"></a>阻塞队列DelayedWorkQueue的实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">offer</span><span class="params">(Runnable x)</span> </span>&#123;</div><div class="line">            <span class="keyword">if</span> (x == <span class="keyword">null</span>)</div><div class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();</div><div class="line">            RunnableScheduledFuture&lt;?&gt; e = (RunnableScheduledFuture&lt;?&gt;)x;</div><div class="line">            <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">this</span>.lock;</div><div class="line">            lock.lock();</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                <span class="keyword">int</span> i = size;</div><div class="line">                <span class="keyword">if</span> (i &gt;= queue.length)</div><div class="line">                    grow();		<span class="comment">//重建数组，长度增加50%</span></div><div class="line">                size = i + <span class="number">1</span>;	</div><div class="line">                <span class="keyword">if</span> (i == <span class="number">0</span>) &#123;</div><div class="line">                    queue[<span class="number">0</span>] = e;</div><div class="line">                    setIndex(e, <span class="number">0</span>);</div><div class="line">                &#125; <span class="keyword">else</span> &#123;</div><div class="line">                    siftUp(i, e);</div><div class="line">                &#125;</div><div class="line">                <span class="keyword">if</span> (queue[<span class="number">0</span>] == e) &#123;</div><div class="line">                    leader = <span class="keyword">null</span>;</div><div class="line">                    available.signal();</div><div class="line">                &#125;</div><div class="line">            &#125; <span class="keyword">finally</span> &#123;</div><div class="line">                lock.unlock();</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">        &#125;</div><div class="line"></div><div class="line"><span class="comment">//这点跟Timer中的操作比较类似，做了一个相对排序而非绝对意义的排序。</span></div><div class="line"><span class="comment">//内部做了一个比较接口，根据下次执行的时间来排队。</span></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">siftUp</span><span class="params">(<span class="keyword">int</span> k, RunnableScheduledFuture&lt;?&gt; key)</span> </span>&#123;</div><div class="line">            <span class="keyword">while</span> (k &gt; <span class="number">0</span>) &#123;</div><div class="line">                <span class="keyword">int</span> parent = (k - <span class="number">1</span>) &gt;&gt;&gt; <span class="number">1</span>;</div><div class="line">                RunnableScheduledFuture&lt;?&gt; e = queue[parent];</div><div class="line">                <span class="keyword">if</span> (key.compareTo(e) &gt;= <span class="number">0</span>)</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                queue[k] = e;</div><div class="line">                setIndex(e, k);</div><div class="line">                k = parent;</div><div class="line">            &#125;</div><div class="line">            queue[k] = key;</div><div class="line">            setIndex(key, k);</div><div class="line">        &#125;</div><div class="line"></div><div class="line"><span class="comment">//但是显然offer并没有来提供延迟调度的实现，真正的延迟调度的实现是在take中完成的。</span></div><div class="line"></div><div class="line"> <span class="keyword">public</span> RunnableScheduledFuture&lt;?&gt; take() <span class="keyword">throws</span> InterruptedException &#123;</div><div class="line">            <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">this</span>.lock;</div><div class="line">            lock.lockInterruptibly();</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                <span class="keyword">for</span> (;;) &#123;</div><div class="line">                    RunnableScheduledFuture&lt;?&gt; first = queue[<span class="number">0</span>];	<span class="comment">//第一个元素，也就是优先级最高，最应该被执行的任务</span></div><div class="line">                    <span class="keyword">if</span> (first == <span class="keyword">null</span>)</div><div class="line">                        available.await();	<span class="comment">//进入这里说明队列中没有待执行的任务，所以来取任务的worker进入等待状态</span></div><div class="line">                    <span class="keyword">else</span> &#123;</div><div class="line">                        <span class="keyword">long</span> delay = first.getDelay(NANOSECONDS);	<span class="comment">//取到任务，getDelay定义于内部类ScheduledFutureTask中</span></div><div class="line">                        <span class="keyword">if</span> (delay &lt;= <span class="number">0</span>)</div><div class="line">                            <span class="keyword">return</span> finishPoll(first);				<span class="comment">//下面有说明，建议先看下面</span></div><div class="line">                        first = <span class="keyword">null</span>; <span class="comment">// don't retain ref while waiting</span></div><div class="line">                        <span class="keyword">if</span> (leader != <span class="keyword">null</span>)</div><div class="line">                            available.await();</div><div class="line">                        <span class="keyword">else</span> &#123;</div><div class="line">                            Thread thisThread = Thread.currentThread();</div><div class="line">                            leader = thisThread;</div><div class="line">                            <span class="keyword">try</span> &#123;</div><div class="line">                                available.awaitNanos(delay);	    <span class="comment">//进入这里说明，当前还未到该任务下次执行的时间，所以进入等待，等待时长为当前到执行时间的时差</span></div><div class="line">                            &#125; <span class="keyword">finally</span> &#123;</div><div class="line">                                <span class="keyword">if</span> (leader == thisThread)</div><div class="line">                                    leader = <span class="keyword">null</span>;</div><div class="line">                            &#125;</div><div class="line">                        &#125;</div><div class="line">                    &#125;</div><div class="line">                &#125;</div><div class="line">            &#125; <span class="keyword">finally</span> &#123;</div><div class="line">                <span class="keyword">if</span> (leader == <span class="keyword">null</span> &amp;&amp; queue[<span class="number">0</span>] != <span class="keyword">null</span>)</div><div class="line">                    available.signal();</div><div class="line">                lock.unlock();</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line"></div><div class="line"><span class="comment">//其目的是计算出下次将要执行任务的时间与当前系统时间的差值。</span></div><div class="line"><span class="comment">//若小于等于0，则说明该立即被执行。</span></div><div class="line"><span class="comment">//否则说明仍需等待。</span></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">getDelay</span><span class="params">(TimeUnit unit)</span> </span>&#123;</div><div class="line">            <span class="keyword">return</span> unit.convert(time - now(), NANOSECONDS);</div><div class="line">        &#125;</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">//返回第一个task,并将第一个元素与最后一个元素互换位置。</span></div><div class="line"><span class="comment">//通常因为我们在offer一个task的时候已经进行过相对排序，使得这个队列在大体上是相对有序的。</span></div><div class="line"><span class="comment">//而这里在take走一个元素后却将最后一个元素（理论上来说，无论是优先级是相对低的，下次执行时间都是最久的）互换。</span></div><div class="line"> <span class="keyword">private</span> RunnableScheduledFuture&lt;?&gt; finishPoll(RunnableScheduledFuture&lt;?&gt; f) &#123;</div><div class="line">            <span class="keyword">int</span> s = --size;		</div><div class="line">            RunnableScheduledFuture&lt;?&gt; x = queue[s];</div><div class="line">            queue[s] = <span class="keyword">null</span>;</div><div class="line">            <span class="keyword">if</span> (s != <span class="number">0</span>)</div><div class="line">                siftDown(<span class="number">0</span>, x);</div><div class="line">            setIndex(f, -<span class="number">1</span>);</div><div class="line">            <span class="keyword">return</span> f;</div><div class="line">        &#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">siftDown</span><span class="params">(<span class="keyword">int</span> k, RunnableScheduledFuture&lt;?&gt; key)</span> </span>&#123;</div><div class="line">            <span class="keyword">int</span> half = size &gt;&gt;&gt; <span class="number">1</span>;</div><div class="line">            <span class="keyword">while</span> (k &lt; half) &#123;</div><div class="line">                <span class="keyword">int</span> child = (k &lt;&lt; <span class="number">1</span>) + <span class="number">1</span>;</div><div class="line">                RunnableScheduledFuture&lt;?&gt; c = queue[child];</div><div class="line">                <span class="keyword">int</span> right = child + <span class="number">1</span>;</div><div class="line">                <span class="keyword">if</span> (right &lt; size &amp;&amp; c.compareTo(queue[right]) &gt; <span class="number">0</span>)</div><div class="line">                    c = queue[child = right];</div><div class="line">                <span class="keyword">if</span> (key.compareTo(c) &lt;= <span class="number">0</span>)</div><div class="line">                    <span class="keyword">break</span>;</div><div class="line">                queue[k] = c;</div><div class="line">                setIndex(c, k);</div><div class="line">                k = child;</div><div class="line">            &#125;</div><div class="line">            queue[k] = key;</div><div class="line">            setIndex(key, k);</div><div class="line">        &#125;</div></pre></td></tr></table></figure>
<blockquote>
<p>siftDown()大体上是一个自顶向下的一个相对排序。<br>首先half = size &gt;&gt;&gt; 1 = size/2。<br>其次，关注whlie(k &lt; half),我们假设永不会走到break，下面我简单的列出部分数组下标变化情况。<br>假设 size = 32。<br>| k        | child   |  right  |<br>| :——–:   | :—–:  | :—-:  |<br>| 0        | 1       |   2 |<br>| 1        |  3      |   4 |<br>| 3        |    7    |   8 |<br>| 7        | 15      |   16 |<br>| 15        |  31      |   32 |<br>由于条件是k &lt; half<br>所以至多循环log2(size)次。<br>类比于siftUp，其实是一次自顶向下的相对排序，结果也会是相对有序，我猜可能是为了弥补siftUp()时的不足，所以再进行了一次相对排序。<br>至此，已经从大体上了解了DelayedWorkQueue是如何实现延迟调度的。<br><br><br>最后，在来看下worker取到task之后如何run<br>由于task被ScheduledFutureTask包装，所以我们看的自然是ScheduledFutureTask的run()。</p>
</blockquote>
<hr>
<h2 id="ScheduledFutureTask控制调度过程"><a href="#ScheduledFutureTask控制调度过程" class="headerlink" title="ScheduledFutureTask控制调度过程"></a>ScheduledFutureTask控制调度过程</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">boolean</span> periodic = isPeriodic();	<span class="comment">//判断是否是一个循环任务</span></div><div class="line">        <span class="keyword">if</span> (!canRunInCurrentRunState(periodic))</div><div class="line">            cancel(<span class="keyword">false</span>);</div><div class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (!periodic)</div><div class="line">            ScheduledFutureTask.<span class="keyword">super</span>.run();	<span class="comment">//若不是循环任务，当做一个普通任务来处理</span></div><div class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (ScheduledFutureTask.<span class="keyword">super</span>.runAndReset()) &#123;	<span class="comment">//若是循环任务，在runAndReset()中实际运行，运行完毕后同时将status重新置为NEW，也就是相当于一个新task</span></div><div class="line">            setNextRunTime();		<span class="comment">//计算下次任务执行的时间，这里与Timer有所区别，Timer是先计算出来在运行，而这里是先运行在计算</span></div><div class="line">            reExecutePeriodic(outerTask);		<span class="comment">//自然，它完成的就是讲task重新放入队列，并做一些线程池状态的相关判断</span></div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<hr>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><blockquote>
<p>1.延迟调度由DelayedWorkQueue来实现。<br>2.Executors.callable()完成Runnable到Callable的转换（适配）。<br>3.ScheduledFutureTask包装task，实现循环任务的“循环”处理，延迟计算，调度控制等相关操作。<br>4.ThreadPoolExecutor实现多线程并发操作。<br>5.相比于Time，最为明显的几点：<br>    1.Timer单线程，ScheduledThreadPoolExecutor多线程（显而易见）。<br>      2.Timer先计算下次调度时间，在运行，ScheduledThreadPoolExecutor相反。<br>      3.Timer之间无法实现TimerTask共享，ScheduledThreadPoolExecutor通过ThreadPoolExecutor可以实现。<br>      4.Timer与ScheduledThreadPoolExecutor使用的BlockingQueue不同。</p>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag">#java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/28/java定时任务（1）/" rel="next" title="java定时任务（1）">
                <i class="fa fa-chevron-left"></i> java定时任务（1）
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/29/java编程建议-1/" rel="prev" title="java编程建议">
                java编程建议 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/08/28/java定时任务（2）/"
           data-title="java定时任务（2）" data-url="http://yoursite.com/2016/08/28/java定时任务（2）/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/touxiang.jpg"
               alt="钱伟峰" />
          <p class="site-author-name" itemprop="name">钱伟峰</p>
          <p class="site-description motion-element" itemprop="description">每天进步一点点</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">21</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#ScheduledThreadPoolExecutor调度方式"><span class="nav-number">1.</span> <span class="nav-text">ScheduledThreadPoolExecutor调度方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#阻塞队列DelayedWorkQueue的实现"><span class="nav-number">2.</span> <span class="nav-text">阻塞队列DelayedWorkQueue的实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ScheduledFutureTask控制调度过程"><span class="nav-number">3.</span> <span class="nav-text">ScheduledFutureTask控制调度过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钱伟峰</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"qianweifeng"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
